<template>
  <div class="video-view">
    <van-pull-refresh v-model="isLoading" @refresh="onRefresh" success-text="刷新成功">
      <keep-alive>
        <masonry-view :DataArr="recommendedVideoDataArr" :video="true" :switchSelected="switchSelected" />
      </keep-alive>

      <wd-infinite-load
        ref="loadmore"
        @loadmore="loadmore"
        :offset="10"
        :immediate-check="false"
        :loading="loading"
      ></wd-infinite-load>
    </van-pull-refresh>
  </div>
</template>

<script>
import { get_recommended_video } from "@/apis/http.js"; //首先，引入http.js中暴露的获取用户的方法
import MasonryView from "@/components/HomeComponents/FoundComponents/MasonryView.vue";
export default {
  name: "VideoView", //视频页
  components: { MasonryView },
  data() {
    return {
      time: 5,
      loading: false,
      isLoading: false,
      recommendedVideoDataArr: []
    };
  },
  mounted() {
    this.getNewRecommendedVideo();
  },
  methods: {
    //第二步  在自定义方法中调用get_users方法，通过async和awit搭配直接获取到数据
    async getNewRecommendedVideo() {
      //通过路由传参的形式，请求数据！！！ {data:res}直接结构赋值出来data给res
      let { data: res } = await get_recommended_video();
      // console.log(res); // 这样就获取到了请求的所有数据！
      this.recommendedVideoDataArr = res.list;
      //后续就可以通过赋值的方式，在页面上渲染数据。
    },

    async getRecommendedVideo() {
      //通过路由传参的形式，请求数据！！！ {data:res}直接结构赋值出来data给res
      let { data: res } = await get_recommended_video();
      // console.log(res); // 这样就获取到了请求的所有数据！
      this.recommendedVideoDataArr.push(...res.list);
      //后续就可以通过赋值的方式，在页面上渲染数据。
    },

    onRefresh() {
      setTimeout(() => {
        this.$nextTick(() => {
          this.isLoading = false;
          this.getNewRecommendedVideo();
        });
      }, 1000);
    },

    loadmore() {
      this.loading = true;

      if (this.time) {
        setTimeout(() => {
          this.getRecommendedVideo();
          this.loading = false;
          // 模拟请求，请求3次，3次结束后设置加载结束
          this.time--;
        }, 1000);
      } else {
        this.$refs.loadmore.loadEnd();
      }
    },

    switchSelected(id) {
      this.$nextTick(() => {
        this.recommendedVideoDataArr.forEach(r => {
          if (r.itemId === id) {
            if (r.postData.postCount.viewCount == 1) {
              r.postData.postCount.viewCount = 0;
              r.postData.postCount.favoriteCount -= 1;
            } else {
              r.postData.postCount.viewCount = 1;
              r.postData.postCount.favoriteCount += 1;
            }
          }
        });

        this.$store.commit("toggleMyLike", id);
        console.log(this.$store.state.myLike);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.video-view {
  width: 100vw;
  min-height: 100vh;
  margin-bottom: 55px;
}
</style>